<?php
namespace plugins\site_config\controller;
use cmf\controller\PluginAdminBaseController;
use plugins\site_config\model\SiteConfigHpcModel;
use plugins\site_config\model\SiteConfigMbModel;
use plugins\site_config\lib\Common as LCOM;
use app\common\lib\model_operate\Tools;


//站点配置首页
class HomePageConfigController extends PluginAdminBaseController
{
    
    const TYPE = [ 'slidshow' ,  'column' , 'ceramicchip' , 'startpage' ];
    const TYPE_STR =["轮播图",'栏目','瓷片区','启动页'];
    //首页配置
    public function index()
    {
        
        $this->assign( 'search' , $this->getSearch() );
        

        return $this->fetch( );
    }
    
    private function getSearch()
    {
        $param = $this->request->param();
 
        $search = [
            'type' => isset( $param [ 'type' ] ) ? $param [ 'type' ] : 0,
            'keywords' => isset( $param [ 'keywords' ] ) ? $param [ 'keywords' ] : '',
            "pagesize" => isset( $param [ 'pagesize' ] )  ? $param [ 'pagesize' ]   : 20,
        ];
        return $search; 
    }
    
    //获取列表
    public function getList()
    {

        $search = $this->getSearch();
        
        $list = SiteConfigHpcModel::where( 'type' , $search[ 'type' ] )->order( 'list_order' );
        
        if( !empty( $search [ 'keywords' ] ) ){
            $kw = $search [ 'keywords' ]; 
            $list = $list->where( 'title|introductory' , 'like' , "%$kw%");
        }
        
        $list = $list->paginates( $search['pagesize'] );
  
        return api_json_echo( true , '成功' , $list  );

    }
    
    //添加配置
    public function addConfig()
    {
        $param = $this->request->param();
        $this->assign( 'type' , $param [ 'type' ]  );
        return $this->fetch();
    }
    
    public function postConfig()
    {
        $param = $this->request->param();
        $data = $param[ 'data' ];
        if( (new SiteConfigHpcModel())->saveAll( $data ) ){
            return api_json_echo( true , '保存成功'  );
        }
        return api_json_echo( false , '保存失败');
    }
    
    public function delConfig()
    {
        $data = $this->request->param();
        $id = $data[ 'id' ];
        if( !empty( $id ) ){
            if( !is_array( $id ) ){
                $id = [ $id ];
            }
            if( SiteConfigHpcModel::where( 'id' , "IN" , $id )-> delete() ){
                return api_json_echo( true , '删除成功' );
            }
        }
        return api_json_echo( false , '删除失败' );
    }
    
    //上传图标
    public function imageup()
    {
        $data = $this->request->param();
        if( empty( $_FILES ) ){
            return api_json_echo( false , '未获取到数据' );
        }
        $path = '/upload/site_config/image';
        $rule = [ 
            'size' => 1024*1024,    //1024kb
            'ext' =>['jpeg' , 'png' , 'jpg' ],
            'type' => [ 'image/jpeg' , 'image/png' , 'image/jpg' ]
        ];
        
        $res = uploadImg( $_FILES [ 'file' ] , $path , $rule  );
        
        if( !$res[ 'status' ] ){
            return api_json_echo( false , '上传失败' , $res [ 'message' ] , $res [ 'code' ] );
        }
        return api_json_echo( true , '上传成功' , $res [ 'data' ] );
    }
    
    //修改配置
    public function editConfig()
    {
        $param = $this->request->param();
        
        $id = $param [ 'id' ];
        $config = SiteConfigHpcModel::get( $id );
        $this->assign( 'config' , $config );
        return $this->fetch();
    }
    
    public function postEditConfig()
    {
        $param = $this->request->param();
        
        $data = $param [ 'data' ];
        if( ( new SiteConfigHpcModel() )->allowField( true )->isUpdate( true )->save( $data ) ){
            return api_json_echo( true , '保存成功' );
        }
        return api_json_echo( false , '保存失败' );
    }
    
    //排序
    public function listOrder( )
    {
        $param = $this->request->param();
        $data = $param [ 'list' ];
        $obj = new SiteConfigHpcModel();
        foreach ( $data as $arr ){
            $obj->isUpdate( true )->save( $arr );
        }
        return api_json_echo( true , '操作成功' );
    }
    



////////////////////////////////////////////////////////////////////////////
    
    //获取模板列表
    public function getMbList()
    {
        $search = $this->getSearch();
        
        $list = SiteConfigMbModel::order( 'id desc' );
        
        if( $search [ 'type' ] != 100 ){
            $lsit = $list->where( 'type' , $search[ 'type' ] );
        }
        
        if( !empty( $search [ 'keywords' ] ) ){
            $kw = $search [ 'keywords' ]; 
            $list = $list->where( 'name' , 'like' , "%$kw%");
        }
        
        $list = $list->paginates( $search[ 'pagesize' ] , false  , [ 'query'=>$search ] );
        
  
        return api_json_echo( true , '成功' , $list  );
    }
    
    
    //添加模板
    public function addMb()
    {
        $param = $this->request->param();
        
        return $this->fetch("addmb" , 
            [
                'mb' => ["轮播图",'栏目','瓷片区','启动页'],
                'type' => $param [ 'type' ]
            ]
        );
    }
    
    //添加模板
    public function editMb( $id )
    {
        $param = $this->request->param();
        $mbobj = SiteConfigMbModel::get( $id );
        
        $model = Tools::tableToModel( $mbobj->table_name );

        $select = [
            'relevance_id' =>'',
            'name' => '',
            'img' => '',
            'introductory' => '',
            'store_id' => '',
        ];
        if( isset( $mbobj->field_map ) ){
            $mbobj->field_map = json_decode( $mbobj->field_map , true );   
        }
        if( $model && !empty( $model ) ){
            $tableInfo = $model->getTableInfo();

            if( isset( $tableInfo [ 'fields' ] ) ){
                $select = [
                    'relevance_id' => $this->makeselect( $tableInfo [ 'fields' ] , isset( $mbobj->field_map[ 'relevance_id' ] ) ?  $mbobj->field_map[ 'relevance_id' ] : '' ),
                    'title' => $this->makeselect( $tableInfo [ 'fields' ] , isset( $mbobj->field_map[ 'title' ] ) ?  $mbobj->field_map[ 'title' ] : '' ),
                    'img' => $this->makeselect( $tableInfo [ 'fields' ] , isset( $mbobj->field_map[ 'img' ] ) ?  $mbobj->field_map[ 'img' ] : '' ),
                    'introductory' => $this->makeselect( $tableInfo [ 'fields' ] , isset( $mbobj->field_map[ 'introductory' ] ) ?  $mbobj->field_map[ 'introductory' ] : '' ),
                    'store_id' => $this->makeselect( $tableInfo [ 'fields' ] , isset( $mbobj->field_map[ 'store_id' ] ) ?  $mbobj->field_map[ 'store_id' ] : '' ),
                ];
            }
        }
        return $this->fetch("editmb" , 
            [
                'mbobj' => $mbobj,
                'mb' => ["轮播图",'栏目','瓷片区','启动页'],
                'select' => $select,
            ]
        );
    }
    
    private function makeselect( $fields , $selected )
    {
        $select = '<select class="">';
        $select .= '<option value="">请选择对应的字段</option>';
        foreach ( $fields as $key => $value ){
            $sed =  $value == $selected ? "selected" : '';
            $select .= '<option value="'.$value.'"   '.$sed.' >'.$value.'</option>';
        }
        $select .= '</select>';
        return $select;
    }
    
    //保存模板
    public function saveMbEdite()
    {
        $param = $this->request->param();
        $param[ 'data' ] [ 'field_map' ] = isset( $param[ 'data' ] [ 'field_map' ] ) ? json_encode( $param[ 'data' ] [ 'field_map' ] , JSON_UNESCAPED_UNICODE ) : ''; 
        
        
        $model = new SiteConfigMbModel();
        
        $param [ 'data' ] [ 'type_name' ] = static::TYPE_STR[ $param [ 'data' ] [ 'type' ] ];
        $res = $model->allowField( true )->isUpdate( true )->save( $param [ 'data' ] );
        if( !$res ){
            return api_json_echo( false , '保存失败,请稍后再试' );
        }
        return api_json_echo( true , '保存成功' );
    }
    
    
    //保存模板
    public function saveMb()
    {
        $param = $this->request->param();
        
        $param[ 'data' ] [ 'field_map' ] = isset( $param[ 'data' ] [ 'field_map' ] ) ? json_encode( $param[ 'data' ] [ 'field_map' ] , JSON_UNESCAPED_UNICODE ) : ''; 
        
        $model = new SiteConfigMbModel();
        
        $param [ 'data' ] [ 'type_name' ] = static::TYPE_STR[ $param [ 'data' ] [ 'type' ] ];
        $res = $model->allowField( true )->isUpdate( false )->save( $param [ 'data' ] );
        if( !$res ){
            return api_json_echo( false , '保存失败,请稍后再试' );
        }
        return api_json_echo( true , '保存成功' );
    }
    
    
 
    
    //模板列表
    public function mbList()
    {
        $param = $this->request->param();
        
        return $this->fetch("mblist" , 
            [
                'mb' => static::TYPE,
                'type' => static::TYPE_STR,
                'search' => $this->getSearch()
            ]
        );
    }
    
    
    //获取表信息
    public function getTbInfo( $tableName )
    {
        $model = Tools::tableToModel( $tableName );
        if( !$model ){
            return api_json_echo( false , '由于输入的表未定义模型,因此未获取到信息' );
        }
        $tableInfo = $model->getTableInfo();
        if( isset( $tableInfo [ 'fields' ] ) ){
            $select = '<select class="">';
            $select .= '<option value="">请选择对应的字段</option>';
            foreach ( $tableInfo [ 'fields' ]  as $key => $value ){
                $select .= '<option value="'.$value.'">'.$value.'</option>';
            }
            $select .= '</select>';
            
            return api_json_echo( true , '获取数据成功' ,  $select );
        }
        return api_json_echo( false , '由于输入的表未定义模型,因此未获取到信息' );
    }
    
    
    //删除模板
    
    public function delete()
    {
        $data = $this->request->param();
        $id = $data[ 'id' ];
        if( !empty( $id ) ){
            if( !is_array( $id ) ){
                $id = [ $id ];
            }
            if( SiteConfigMbModel::where( 'id' , "IN" , $id )-> delete() ){
                return api_json_echo( true , '删除成功' );
            }
        }
        return api_json_echo( false , '删除失败' );
    }
    
    
    
    //添加模板数据页面
    public function mbConfigAdd()
    {
        $param = $this->request->param();

        $type = $param [ 'type' ];
        
        $mblist = SiteConfigMbModel::where( 'type' , $type )->select();
        
        
        $store = Tools::tableToModel( 'cmf_store' );
        $storelist = [];
        if( $store ){
            $storelist = $store::select();
        }
        
        $this->assign( 'storelist', $storelist );
        $this->assign( 'mblist' , $mblist );
        return $this->fetch( 'home_page_config/mb_config/mbconfigaddpage' );
    }
    
    //添加模板数据页面 获取数据
    public function getData()
    {
        $param = $this->request->param();
        
        $storeId   = isset( $param [ 'store_id' ] ) ? $param [ 'store_id' ] : 'qb';
        $mbId      = isset( $param [ 'mb_id' ] ) ? $param [ 'mb_id' ] : '';
        $field      = isset( $param [ 'field' ] ) ? $param [ 'field' ] : '';
        $keywords   = isset( $param [ 'keywords' ] ) ? $param [ 'keywords' ] : '';
        $type       = isset( $param [ 'type' ] ) ? $param [ 'type' ] : '';
        
        $pagesize = isset( $param [ 'limit' ] ) ? $param [ 'limit' ] : 20 ;

        $list = [];
        $moban = SiteConfigMbModel::get( $mbId );
        if( !empty( $moban->table_name ) ){
            $fieldMap = json_decode( $moban->field_map , true );
            $tbname = Tools::tableNameFormat( $moban->table_name, $type = 0);
            $list = Db( $tbname );//->where( 'id' , $mbId )->select();
            if( isset( $fieldMap [ 'store_id' ] ) && !empty(  $fieldMap [ 'store_id' ] ) && $storeId != 'qb'  ){
                $list = $list->where( $fieldMap[ 'store_id' ] , $storeId );
            }
            if( !empty( $keywords ) ){
                $where = '';
                $all   = [];
                switch ( $field ) {
                    case 'title':
                            if( isset( $fieldMap [ 'title' ] ) && !empty(  $fieldMap [ 'title' ] ) ){
                                $all [] = $fieldMap [ 'title' ];
                                $where =  $fieldMap[ 'title' ] ." like  '%$keywords%'";
                            }
                            
                        break;
                    case 'introductory':
                            if( isset( $fieldMap [ 'introductory' ] ) && !empty(  $fieldMap [ 'introductory' ] ) ){
                                $all [] = $fieldMap [ 'introductory' ];
                                $where =  $fieldMap[ 'introductory' ] ." like  '%$keywords%'";
                            }
                            
                        break;
                        
                    default:
                            if( !empty( $all ) ){
                                $where = implode( '|' , $all )." like  '%$keywords%'";
                            }
                        break;
                }
                if( !empty( $where ) ){
                    $list = $list -> where( $where );
                }
            }
            
            $list = $list -> paginates( $pagesize );
            
            $arr = $this->formatData( $list , $fieldMap );
            
            $data = [
                'total' => $list->total(),
                'data' => $arr
            ];
            return api_json_echo( true , '成功' , $data );
            
        }
        
        return api_json_echo( true , '成功' , ['total'=>0,'data'=>''] );
    } 
    
    
    private function formatData( $list , $fieldMap )
    {
        $arr = [];
        foreach ( $list as $key => $value ){
            $tmp = [
                'relevance_id'  => $this->getValue( $value , $fieldMap , 'relevance_id' ),
                'title'         => $this->getValue( $value , $fieldMap , 'title' ),
                'img'         => $this->getValue( $value , $fieldMap , 'img' ),
                'introductory'  => $this->getValue( $value , $fieldMap , 'introductory' ),
                'addr'          => $this->getValue( $value , $fieldMap , 'addr' ),
                'addr_type'     => $this->getValue( $value , $fieldMap , 'addr_type' ),
                'delay'         => $this->getValue( $value , $fieldMap , 'delay' ),
                'status'        => $this->getValue( $value , $fieldMap , 'status' ),

            ];
            $arr [] = $tmp;
            
        }
        return $arr;
    }
    
    private function getValue( $value , $fieldMap , $field )
    {
        $str = '';
        if( isset( $fieldMap [ $field ] ) && !empty( $fieldMap [ $field ] ) ){
            $keys = array_keys( $value );

            $tmp = $fieldMap [ $field ];

            if( in_array( $fieldMap[ $field ] , $keys ) ){
                $str = empty( $value [ $tmp ] ) ? '' : strip_tags( autoHtmlspecialcharsDecode( $value [ $tmp ] ) );
            }else{
                $str = $tmp;
            }
        }
        return $str;
    }
    
    
    
    
    
}